{% extends "base.html" %}
{% load static %}
{% load display_tags %}
{% block content %}
    {{ block.super }}
    <link href="{% static "google-code-prettify/src/prettify.css" %}" rel="stylesheet"/>
    <div class="row">
        <div class="col-md-8">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <div class="clearfix">
                        <h4 class="pull-left">Report Format</h4>
                    </div>
                </div>
                <div class="panel-body in-use-widgets">
                    <ul id="sortable2">
                        {% for widget in in_use_widgets %}
                            <li class="{{ widget.widget_class }}">
                                {{ widget.get_option_form }}
                            </li>
                        {% endfor %}
                    </ul>
                </div>
                <div class="panel-footer">
                    <div class="clearfix">
                        <a class="btn btn-success disabled pull-right run_report" href="#" data-toggle="tooltip" title="Add at least one section from Available Widgets before running." style="pointer-events: auto;">Run</a>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h4>Available Widgets</h4>
                </div>
                <div class="panel-body available-widgets">
                    <ul id="sortable1">
                        {% for widget in available_widgets %}
                            <li class="{{ widget.widget_class }}">
                                {{ widget.get_option_form }}
                            </li>
                        {% endfor %}
                    </ul>
                </div>
            </div>
        </div>
        <form id="custom_report" class="hidden" action="{% url 'custom_report' %}" method="post">
            {% csrf_token %}
            <textarea name="json" id="json"></textarea>
        </form>
    </div>
{% endblock %}
{% block postscript %}
    {{ block.super }}
    <script src="{% static "jquery.hotkeys/jquery.hotkeys.js" %}"></script>
    <script src="{% static "google-code-prettify/src/prettify.js" %}"></script>
    <script src="{% static "bootstrap-wysiwyg/src/bootstrap-wysiwyg.js" %}"></script>
    <script>
        function setUpFindingFilters() {
            $(".report-filter-set :input").not("button").addClass("form-control input-sm");
            $(".report-filter-set label").css("display", "block");

            $(".report-filter-set input[type=text]").each(function () {
                var id = this.id;
                if (id) {
                    var label = $("label[for=" + id + "]");
                    if (label && label.html()) {
                        $(this).attr("placeholder", label.html().replace(':', "..."));
                    }
                }
            });

            $('.report-filter-set select[multiple=multiple]').each(function () {
                var id = this.id;
                if (id) {
                    var label = $("label[for=" + id + "]");
                    if (label && label.html()){
                        $(this).chosen({
                            'placeholder_text_multiple': label.html().replace(':', "..."),
                            'width': '200px !important'
                        });
                    }
                }
            });

            if ($('.in-use-widgets ul#sortable2 li').not('.report-options').length > 0) {
                var $run = $('a.run_report');
                $run.removeClass('disabled')
                    .css('pointer-events', '')
                    .attr('title', 'Run the report')
                    .attr('data-original-title', 'Run the report');
            }
            else {
                var $run = $('a.run_report');
                $run.addClass('disabled')
                    .css('pointer-events', 'auto')
                    .attr('title', 'Add at least one section from "Available Widgets" before running.')
                    .attr('data-original-title', 'Add at least one section from "Available Widgets" before running.');
            }
        }

        function initWysiwyg($we) {
            const $toolbar = $we.find("[data-role=editor-toolbar]"),
                $ed = $we.find(".editor");
            $ed.removeAttr('id');
            $ed.uniqueId();
            const toolbarId = `editor-toolbar-${$ed.prop('id')}`;
            $toolbar.attr("data-role", toolbarId);
            $ed.wysiwyg({toolbarSelector: `[data-role=${toolbarId}]`});
        }

        function resetWidgetToAvailable(item) {
            // Remove the widget altogether if it supports multiple instances (an entry already exists in the list)
            if (item.children(":first").data("multiple")) {
                item.fadeOut('slow', function () {
                    $(this).remove()
                });
                return;
            }
            item.find(".icon").removeClass("icon-grab-reorder").addClass("fa-arrows");
            item.find('[data-toggle="tooltip"]').tooltip('destroy');
            item.find('[data-toggle="tooltip"]').attr('title', 'Click and drag to move')
            item.find('[data-toggle="tooltip"]').tooltip();
            item.find('[data-toggle="tooltip"]').tooltip('hide');
            item.find('.delete-widget').remove();
        }

        function removeInUseWidget($widget) {
            // This would probably have been more straightforward if triggers on the sortable worked, but... they
            // don't seem to.

            // Append the widget to our 'available list'
            $('.available-widgets > ul').append($widget);
            // Run the reset functionality to make it pretty/handle multiple instances etc.
            resetWidgetToAvailable($widget);
        }

        function addWidgetRemoveButton(item) {
            const $removeButton = $('<i/>')
                .addClass('fa-solid fa-trash pull-right delete-widget')
                .css('margin-right', '10px')
                .attr('title', 'Click to remove this widget.')
                .attr('data-toggle', 'tooltip')
                .click((evt) => {
                    evt.preventDefault();
                    evt.stopPropagation();
                    if (confirm('Are you sure you want to remove this widget?'))
                    {
                        removeInUseWidget($(evt.target).closest('li'));
                    }
                })
                .tooltip()
                // Hide/show the parent container tooltip appropriately so we don't double up
                .mouseover(evt => $(evt.target).closest('div.panel-heading').tooltip('hide'))
                .mouseleave(evt => $(evt.target).closest('div.panel-heading').tooltip('show'));
            item.find('.icon').after($removeButton);
        }

        function runReport(event) {
            var valid = true;

            // Require at least one content widget (exclude report options)
            if ($('.in-use-widgets ul#sortable2 li').not('.report-options').length === 0) {
                alert('Please add at least one section from "Available Widgets" before running.');
                event.preventDefault();
                return;
            }

            $('.in-use-widgets .form-control').not('#finding-list .form-control')
                .not('#endpoint-list .form-control').not('#wysiwyg-content .form-control')
                .not('.bs-searchbox .form-control').not('div').each(function () {
                if ($(this).val() === '')
                    valid = false;
            });

            if (valid) {

                var result = [];
                $('.in-use-widgets form').each(function () {  // loop start for each form

                    var _form = $(this);

                    $(this).find('.editor').each(function () {
                        _form.find('input[name="hidden_content"]').attr('value', $(this).html().replace( /(<br>|\s|<div><br><\/div>|&nbsp;)*$/, ""));
                    });

                    sr = $(this).serializeArray();

                    var y = {};
                    y[this.id] = sr;
                    result.push(y);
                });

                var json_content = JSON.stringify(result);

                $('form#custom_report textarea#json').val(json_content);

                $('form#custom_report').removeClass('hidden').submit();
            }
            else {
                alert('Please complete all forms.')
            }

            event.preventDefault();
        }
        // placeholder for report widget scripts injected by Django blocks
        $(function () {
            $(".available-widgets > ul").sortable({
                handle: "div.panel div.panel-heading",
                connectWith: ".in-use-widgets ul",
                placeholder: "ui-state-highlight",
                cursor: 'default',
                opacity: 0.65,
                remove: function (event, ui) {
                    // If the widget supports multiple instances, create a new instance of it in the list
                    if (ui.item.children(":first").data("multiple")) {
                        ui.item.clone().prependTo('.available-widgets ul#sortable1');
                    }
                    ui.item.find('[data-toggle="tooltip"]').tooltip('hide');
                },
                receive: function (event, ui) {
                    resetWidgetToAvailable(ui.item);
                },
                start: function (event, ui) {
                    ui.item.find('[data-toggle="tooltip"]').tooltip('destroy');
                },
            });

            $(".in-use-widgets > ul").sortable({
                handle: "div.panel div.panel-heading",
                connectWith: ".available-widgets ul",
                placeholder: "ui-state-highlight",
                cursor: 'default',
                opacity: 0.65,
                remove: function (event, ui) {
                    ui.item.find('[data-toggle="tooltip"]').tooltip('hide');

                    if ($('.in-use-widgets ul#sortable2 li').not('.report-options').length > 0) {
                        var $run = $('a.run_report');
                        $run.removeClass('disabled')
                            .css('pointer-events', '')
                            .attr('title', 'Run the report')
                            .attr('data-original-title', 'Run the report')
                            .tooltip('fixTitle');
                    }
                    else {
                        var $run = $('a.run_report');
                        $run.addClass('disabled')
                            .css('pointer-events', 'auto')
                            .attr('title', 'Add at least one section from "Available Widgets" before running.')
                            .attr('data-original-title', 'Add at least one section from "Available Widgets" before running.')
                            .tooltip('fixTitle');
                    }
                },
                receive: function(event, ui) {
                    ui.item.find(".icon").addClass("icon-grab-reorder").removeClass("fa-arrows");
                    ui.item.find('[data-toggle="tooltip"]').tooltip('destroy');

                    if (ui.item.find('[data-toggle="tooltip"]').next().length) {
                        ui.item.find('[data-toggle="tooltip"]').attr('title', 'Click and drag to move, click to collapse.')
                    }
                    ui.item.find('[data-toggle="tooltip"]').tooltip();
                    ui.item.find('[data-toggle="tooltip"]').tooltip('hide');

                    if ($('.in-use-widgets ul#sortable2 li').not('.report-options').length > 0) {
                        var $run = $('a.run_report');
                        $run.removeClass('disabled')
                            .css('pointer-events', '')
                            .attr('title', 'Run the report')
                            .attr('data-original-title', 'Run the report')
                            .tooltip('fixTitle');
                    }
                    else {
                        var $run = $('a.run_report');
                        $run.addClass('disabled')
                            .css('pointer-events', 'auto')
                            .attr('title', 'Add at least one section from "Available Widgets" before running.')
                            .attr('data-original-title', 'Add at least one section from "Available Widgets" before running.')
                            .tooltip('fixTitle');
                    }

                    if (ui.item.attr('class') === 'wysiwyg-content') {
                        initWysiwyg(ui.item);
                    }

                    addWidgetRemoveButton(ui.item);
                },
                start: function (event, ui) {
                    ui.item.find('[data-toggle="tooltip"]').tooltip('destroy');
                },
                create: function(event, ui) {
                    // Initialize all existing non-options widgets to have a 'remove' button
                    $(event.target)
                        .children("li")
                        .not(".report-options")
                        .each((i, e) => addWidgetRemoveButton($(e)));
                },
            });

            setUpFindingFilters();

            // Initializes any filter fields in $el
            function filterFieldInit($el) {
                $('select', $el)
                    .addClass('selectpicker')
                    .attr('data-live-search', 'true')
                    .attr('data-container', 'body')
                    .css('width', '70%')
                    .selectpicker('render');
            }

            // Retrieves (report) data at the given url and inserts it as HTMl into $targetEl, and configures filters
            // on the returned data.
            function retrieveReportData(url, $targetEl) {
                $.get(url).done(function (data) {
                    filterFieldInit(
                        $targetEl.html(data)
                    );
                    setUpFindingFilters();
                });
            }

            // --------
            // Findings
            // --------

            // "Apply Filters"
            $(document).on('submit', 'form.finding-list', function (event) {
                const $form = $(this);
                event.preventDefault();
                retrieveReportData(
                    "{% url 'report_findings' %}?" + $form.serialize(),
                    $form.closest('li.finding-list')
                );
            });

            // "Clear filters"
            $(document).on('click', 'form.finding-list a.clear.centered', function (event) {
                const $a = $(this);
                event.preventDefault();
                retrieveReportData("{% url 'report_findings' %}", $a.closest('li.finding-list'));
            });

            // Sort/order columns and Pagination
            $(document).on('click', 'li.finding-list th a, div.finding-pagination a', function (event) {
                const $a = $(this);
                event.preventDefault();
                retrieveReportData("{% url 'report_findings' %}" + $a.attr('href'), $a.closest('li.finding-list'));
            });

            /// --------
            // Endpoints
            // ---------

            // "Apply filters"
            $(document).on('submit', 'form.endpoint-list', function (event) {
                const $form = $(this);
                event.preventDefault();
                retrieveReportData(
                    "{% url 'report_endpoints' %}?" + $form.serialize(),
                    $form.closest('li.endpoint-list')
                );
            });

            // "Clear filters"
            $(document).on('click', 'form.endpoint-list a.clear.centered', function (event) {
                const $a = $(this);
                event.preventDefault();
                retrieveReportData("{% url 'report_endpoints' %}", $a.closest('li.endpoint-list'));
            });

            // Pagination
            $(document).on('click', 'div.endpoint-pagination a', function (event) {
                const $a = $(this);
                event.preventDefault();
                retrieveReportData("{% url 'report_endpoints' %}" + $a.attr('href'), $a.closest('li.endpoint-list'));
            })

            $('[data-toggle="tooltip"]').tooltip({container: 'body', placement: 'top'})

            $(document).on('click', '.in-use-widgets .panel-available-widget .panel-heading', function (event) {
                $(this).siblings('.panel-body').slideToggle();
            });

            $("#sortable2 .wysiwyg-content").each((i, e) => {
                initWysiwyg($(e));
            });

            $('a.run_report').on('click', runReport);
        });
    </script>
{% endblock %}
